<template>
  <!-- 面包屑导航 -->
  <div className="break">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item style="font-size: 22px;padding: 15px 0 0 15px"><b>购物车</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 数据表格 -->
  <div style="margin:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%">
      <el-table-column prop="dname" label="菜品" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="totalprice" label="总价格" />
      <el-table-column label="数量">
        <template #default="{ row }">
          <el-input-number v-model="row.count" :min="1" @change="handleQuantityChange(row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="removeFromCart(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-button type="danger" @click="clearCart">清空购物车</el-button>
  <template v-if="blogInfo.length === 0">
    <div>购物车为空，无法结算</div>
  </template>
  <el-button type="primary" v-else-if="blogInfo.length > 0" @click="goToSettle">结算</el-button>
  <div style="margin: 20px;">
    <p>购物车中共有 {{ blogInfo.length }} 种商品，总价为 {{ totalPrice }} 元</p>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import request from "@/utils/canteen";
import { ElMessage, ElButton } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

const blogInfo = ref([]);
const route = useRoute();
const router = useRouter();

const canSettle = computed(() => {
  return blogInfo.value.length > 0;
});
const getDish = () => {
  request({
    url: '/cart/getAll',
    method: 'get',
  }).then((response) => {
    console.log(response);
    if (response.status === 200) {
      blogInfo.value = response.data;
      console.log('获取到的数据：', blogInfo.value);
      console.log('数据长度：', blogInfo.value.length);
    } else {
      ElMessage.error('请求失败');
    }
  }).catch((error) => {
    console.error("请求失败:", error);
    ElMessage.error('请求失败');
  });
};

const handleQuantityChange = (row) => {
  const newCount = row.count;
  request({
    url: `/cart/${row.id}/quantity`,
    method: 'put',
    params: { newCount },
  }).then((response) => {
    if (response.status === 200) {
      getDish();
      ElMessage.success('更新成功');
    } else {
      ElMessage.error('更新失败');
    }
  }).catch((error) => {
    console.error("更新请求失败:", error);
  });
};

const removeFromCart = (id) => {
  request({
    url: `/cart/${id}`,
    method: 'delete',
  }).then((response) => {
    if (response.status === 200) {
      getDish(); // 重新获取购物车数据
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败');
    }
  }).catch((error) => {
    console.error("删除请求失败:", error);
    ElMessage.error('删除失败');
  });
};

const totalPrice = computed(() => {
  return blogInfo.value.reduce((total, item) => total + item.totalprice , 0);
});

const clearCart = () => {
  request({
    url: '/cart/clear',
    method: 'post',
  }).then((response) => {
    if (response.status === 200) {
      ElMessage.success('购物车已清空');
      blogInfo.value = []; // 清空购物车数据
    } else {
      ElMessage.error('清空失败');
    }
  }).catch((error) => {
    console.error("清空购物车请求失败:", error);
    ElMessage.error('清空购物车失败');
  });
};

const goToSettle = () => {
  router.push({ path: '/home/canteen/settle' });
};

onMounted(() => {
  getDish();
});
</script>

<style scoped>
.el-table {
  border-collapse: collapse;
  border: 1px solid #ddd;
  background-color: #f9f9fa;
  font-size: 14px;
}

.el-table th,
.el-table td {
  padding: 10px;
  border: 1px solid #ddd;
}

.el-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}
</style>